layui.use(['table', 'admin', 'ax', 'func','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var form = layui.form;

    laydate.render({
        elem: '#timeLimit',
        range: true,
        trigger: 'click',
        //max: Feng.currentDate()
    });

    laydate.render({
        elem: '#timeLimitPay',
        range: true,
        trigger: 'click',
        //max: Feng.currentDate()
    });


    //初始化日期
    function format(fmt, date) {
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    var dateFirst = new Date();
    var lastDay = dateFirst.getDate()-1
    dateFirst.setDate(lastDay);
    //dateFirst.setDate(1);
    var firstDay = format('yyyy-MM-dd', dateFirst);
    var times = new Date();
    var today = format('yyyy-MM-dd', times);
    var dateStr = firstDay + " - " + today;
    //todo 测试，正式需要修改为前一天
    //var dateStr = "2021-11-24" + " - " + "2021-11-24";
    $('#timeLimit').val(dateStr);

    /**
     * 管理
     */
    var BtyPaymentOrderYybb = {
        tableId: "BtyPaymentOrderYybbTable"
    };

    /**
     * 初始化表格的列
     */
    BtyPaymentOrderYybb.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            // {field: 'id', hide: true, title: '主键id'},
            {field: 'id', sort: true, title: '序号', width: 100,align: "center", fixed: true},
            {field: 'yyr', sort: true, title: '营业日期', width: 120, fixed: true},
            // {field: 'yybbId', sort: true, title: '日现金表id'},
            {field: 'dianming', sort: true, title: '店名',width: 220, fixed: true},
            {field: 'yaoma', sort: true, title: '妖码',width: 100, fixed: true},

            {field: 'xj', sort: true, title: '现金',width: 100},
            {field: 'xjbz', sort: true, title: '充值现金',width: 110},
            {field: 'bpodPaidCash', sort: true, title: '现金实缴',width: 110},
            {field: 'cashBalance', sort: true,toolbar: '#cashBalanceHtml', title: '现金差额',width: 110},
            {field: 'bpoPayDatetime', sort: true, title: '支付时间',width: 140},
            {field: 'bpoPaidCashAll', sort: true, title: '支付金额',width: 110},
            {field: 'bpoPayMethod', sort: true, title: '支付方式',toolbar: '#payMethodHtml',width: 110},
            {field: 'bpoPayCode', sort: true,width: 110, title: '支付编号'},
            {field: 'bpoOutTradeNo', sort: true,width: 150, title: '木瓜预支付编号'},
            {field: 'bpoSuixingfuShopNum', sort: true,toolbar: '#bpoSuixingfuShopNumHtml', title: '随行付商户编号',width: 150},
            {field: 'payInfo', sort: true,toolbar: '#payInfoHtml', title: '支付明细',width: 100},
            // {field: 'btyPaymentOrderId', sort: true, title: '支付订单表id'},
            // {field: 'payState', sort: true, title: '支付状态（0.支付中，1，支付成功，2支付为失败）'},
            // {field: 'createTime', sort: true, title: '创建时间'},
            // {field: 'createUser', sort: true, title: '创建人'},
            // {field: 'updateTime', sort: true, title: '修改时间'},
            // {field: 'updateUser', sort: true, title: '修改人'},

            {align: 'center', toolbar: '#tableBar', title: '操作', fixed: "right",width: 100}
        ]];
    };




    /**
     * 点击查询按钮
     */
    BtyPaymentOrderYybb.search = function () {
        var timeLimit = $("#timeLimit").val();
        //开始时间
        var startDateTime = timeLimit.substring(0, 10);
        //结束时间
        var endDateTime = timeLimit.replace(" ", "").substring(12, 22);

        //现金差额
        var cashBalance = $("#cashBalance").val();
        //店名或者妖码
        var dmOrYaoma = $("#dmOrYaoma").val();

        // 天财现金有无（空，全部，2有，1无）
        var xjHave = $("#xjHave").val();

        // 天财现金充值有无（空，全部，2有，1无）
        var xjbzHave = $("#xjbzHave").val();

        var timeLimitPay = $("#timeLimitPay").val();

        //开始支付的时间
        var startbpoPayDatetime = timeLimitPay.substring(0, 10);

        if(startbpoPayDatetime){
            startbpoPayDatetime = startbpoPayDatetime + " 00:00:00"
        }

        //结束支付时间
        var endbpoPayDatetime = timeLimitPay.replace(" ", "").substring(12, 22);

        if(endbpoPayDatetime){
            endbpoPayDatetime = endbpoPayDatetime + " 23:59:59"
        }


        //随行付账号
        var suixingfuShopNum = $("#suixingfuShopNum").val();

        //支付渠道 1.乐刷，2.随行付
        var paymentChannel = $("#paymentChannel").val();

        var queryData = {};

        queryData['startDateTime'] = startDateTime;
        queryData['endDateTime'] = endDateTime;
        queryData['cashBalance'] = cashBalance;
        queryData['dm'] = dmOrYaoma;
        queryData['xjHave'] = xjHave;

        queryData['xjbzHave'] = xjbzHave;


        queryData['xjbzHave'] = xjbzHave;


        queryData['startbpoPayDatetime'] = startbpoPayDatetime;
        queryData['endbpoPayDatetime'] = endbpoPayDatetime;

        //随行付账号
        queryData['suixingfuShopNum'] = suixingfuShopNum;
        //支付渠道 1.乐刷，2.随行付
        queryData['paymentChannel'] = paymentChannel;

        table.reload(BtyPaymentOrderYybb.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 跳转到添加页面
     */
    BtyPaymentOrderYybb.jumpAddPage = function () {
        window.location.href = Feng.ctxPath + '/btyPaymentOrderDetails/add'
    };

    /**
    * 跳转到编辑页面
    *
    * @param data 点击按钮时候的行数据
    */
    BtyPaymentOrderYybb.jumpEditPage = function (data) {
        window.location.href = Feng.ctxPath + '/btyPaymentOrderDetails/edit?id=' + data.id
    };

    //提醒店长
    BtyPaymentOrderYybb.onSendMsg=function(){

        var timeLimit = $("#timeLimit").val();
        //开始时间
        var startDateTime = timeLimit.substring(0, 10);
        //结束时间
        var endDateTime = timeLimit.replace(" ", "").substring(12, 22);


        //现金差额
        var cashBalance = $("#cashBalance").val();

        //店名或者妖码
        var dmOrYaoma = $("#dmOrYaoma").val();

        // 天财现金有无（空，全部，2有，1无）
        var xjHave = $("#xjHave").val();

        // 天财现金充值有无（空，全部，2有，1无）
        var xjbzHave = $("#xjbzHave").val();


        var timeLimitPay = $("#timeLimitPay").val();

        //开始支付的时间
        var startbpoPayDatetime = timeLimitPay.substring(0, 10);

        if(startbpoPayDatetime){
            startbpoPayDatetime = startbpoPayDatetime + " 00:00:00"
        }

        //结束支付时间
        var endbpoPayDatetime = timeLimitPay.replace(" ", "").substring(12, 22);

        if(endbpoPayDatetime){
            endbpoPayDatetime = endbpoPayDatetime + " 23:59:59"
        }

        if(startDateTime==null||startDateTime==''||endDateTime==null||endDateTime==''){
            Feng.error("营业日期不能为空");
            return;
        }

        if(cashBalance==null||cashBalance==''){
            Feng.error("现金差额不能为空");
            return
        }

        if(xjHave!=2 && xjbzHave!=2){
            Feng.error("天才现金和充值现金不能都为空或无");
            return;
        }

        if(cashBalance==null||cashBalance==''){
            Feng.error("现金差额不能为空");
            return
        }


        layer.open({
            type: 2,
            title: '店长信息',
            area: ['800px', '600px'],
            content: Feng.ctxPath + '/btyPaymentOrderDetails/searchCashBalance?startDateTime=' + startDateTime +"&endDateTime="+endDateTime+"&cashBalance="+cashBalance +"&dm="+dmOrYaoma+"&xjHave="+xjHave+"&xjbzHave="+xjbzHave +"&startbpoPayDatetime="+startbpoPayDatetime+"&endbpoPayDatetime="+endbpoPayDatetime,
            end: function () {

            }
        });

    }

    /**
     * 导出excel按钮
     */
    BtyPaymentOrderYybb.exportExcel = function () {
        var checkRows = table.checkStatus(BtyPaymentOrderYybb.tableId);
        if (checkRows.data.length === 0) {

            var timeLimit = $("#timeLimit").val();
            //开始时间
            var startDateTime = timeLimit.substring(0, 10);
            //结束时间
            var endDateTime = timeLimit.replace(" ", "").substring(12, 22);

            //现金差额
            var cashBalance = $("#cashBalance").val();
            //店名或者妖码
            var dmOrYaoma = $("#dmOrYaoma").val();
            //店名或者妖码天财现金有无（空，全部，2有，1无）
            var xjHave = $("#xjHave").val();

            // 天财现金充值有无（空，全部，2有，1无）
            var xjbzHave = $("#xjbzHave").val();

            var timeLimitPay = $("#timeLimitPay").val();

            //开始支付的时间
            var startbpoPayDatetime = timeLimitPay.substring(0, 10);

            if(startbpoPayDatetime){
                startbpoPayDatetime = startbpoPayDatetime + " 00:00:00"
            }

            //结束支付时间
            var endbpoPayDatetime = timeLimitPay.replace(" ", "").substring(12, 22);

            if(endbpoPayDatetime){
                endbpoPayDatetime = endbpoPayDatetime + " 23:59:59"
            }

            //随行付账号
            var suixingfuShopNum = $("#suixingfuShopNum").val();

            //支付渠道 1.乐刷，2.随行付
            var paymentChannel = $("#paymentChannel").val();

            var queryData = {};

            queryData['startDateTime'] = startDateTime;
            queryData['endDateTime'] = endDateTime;
            queryData['cashBalance'] = cashBalance;
            queryData['dm'] = dmOrYaoma;
            queryData['xjHave'] = xjHave;

            queryData['xjbzHave'] = xjbzHave;

            queryData['startbpoPayDatetime'] = startbpoPayDatetime;
            queryData['endbpoPayDatetime'] = endbpoPayDatetime;

            queryData['suixingfuShopNum'] = suixingfuShopNum;

            queryData['paymentChannel'] = paymentChannel;

            $.ajax({
                type: "post",
                url: "/btyPaymentOrderDetails/searchPayList",
                datatype: "json",
                async: false,
                data:queryData,
                success: function (data) {
                    //lists = data.data;
                    var lists = data.data;
                    for (index in lists) {
                        var bpoPayCode = lists[index].bpoPayCode;
                        //支付编码
                        lists[index].bpoPayCode = bpoPayCode + "\t";

                        var cashBalance = "";
                        if(bpoPayCode){
                            cashBalance = lists[index].xj+lists[index].xjbz - lists[index].bpodPaidCash;
                        }else{
                            cashBalance = lists[index].xj+lists[index].xjbz
                        }

                        //现金差额
                        lists[index].cashBalance = cashBalance + "\t";

                        var bpoPayMethod = lists[index].bpoPayMethod;

                        if(lists[index].bpoPayMethod == 'SDZF'){
                            bpoPayMethod = "手动添加("+lists[index].bpoManuallyAddUser+")";
                        }

                        if(lists[index].bpoPayMethod == 'WX'){
                            bpoPayMethod = "微信";
                        }

                        //支付方式
                        lists[index].bpoPayMethod = bpoPayMethod + "\t";

                        var bpoSuixingfuShopNum = lists[index].bpoSuixingfuShopNum;
                        //随行付商户号
                        if(bpoSuixingfuShopNum){
                            lists[index].bpoSuixingfuShopNum =  bpoSuixingfuShopNum.substr(-4) + "(完整商户号:"+bpoSuixingfuShopNum+")";
                        }


                    }
                    table.exportFile(tableResult.config.id, lists, 'xls');
                }
            });



        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    BtyPaymentOrderYybb.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btyPaymentOrderDetails/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(BtyPaymentOrderYybb.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    /**
     * 点击查询查询详情
     * @param data
     */
    BtyPaymentOrderYybb.onPayInfoItem=function(data){
        layer.open({
            type: 2,
            title: '账单详情',
            area: ['800px', '400px'],
            content: Feng.ctxPath + '/btyPaymentOrderDetails/btyPaymentOrderDetailsSimple?bpoPayCode=' + data.bpoPayCode+"&dianming="+data.dianming+"&bpoPaidCashAll="+data.bpoPaidCashAll,
            end: function () {
                // $("#pid").val(DeptInfoDlg.data.pid);
                // $("#pName").val(DeptInfoDlg.data.pName);
            }
        });

    }
    /**
     * 手动支付
     * @param data
     */
    BtyPaymentOrderYybb.onManualOperationItem=function(data){
        layer.open({
            type: 2,
            title: '手动支付',
            area: ['380px', '240px'],
            content: Feng.ctxPath + '/btyPaymentOrderDetails/btyPaymentOrderDetailsManualOperation?id=' + data.id+"&xj="+data.xj+"&xjbz="+data.xjbz+"&sumTodayCash="+data.sumTodayCash+"&dianming="+data.dianming+"&yaoma="+data.yaoma+"&yyr="+data.yyr,
            end: function () {
                BtyPaymentOrderYybb.search();
            }
        });
    }

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + BtyPaymentOrderYybb.tableId,
        url: Feng.ctxPath + '/btyPaymentOrderDetails/searchPayPageList',
        page: true,
        height: "full-94",
        limit:20,
        cellMinWidth: 100,
        cols: BtyPaymentOrderYybb.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BtyPaymentOrderYybb.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

    BtyPaymentOrderYybb.jumpAddPage();

    });

    // 导出excel
    $('#btnExp').click(function () {
        BtyPaymentOrderYybb.exportExcel();
    });

    // 提醒店长
    $('#sendMsg').click(function () {
        BtyPaymentOrderYybb.onSendMsg();
    });

    // 工具条点击事件
    table.on('tool(' + BtyPaymentOrderYybb.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            BtyPaymentOrderYybb.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            BtyPaymentOrderYybb.onDeleteItem(data);
        } else if(layEvent ==='payInfo'){
            BtyPaymentOrderYybb.onPayInfoItem(data);
        } else if(layEvent ==='manualOperation'){
            BtyPaymentOrderYybb.onManualOperationItem(data);
        }



    });
    /**
     * 随行付账号查询
     *
     */
    BtyPaymentOrderYybb.searchSuixingfu = function(){
        $.ajax({
            type: "post",
            url: "/btyPaymentOrderDetails/getSuixingfuShopNumList",
            datatype: "json",
            async: false,
            success: function (data) {
                //随行付账号
                $("#suixingfuShopNum").html("<option value=''>全部随行付账号</option>");
                $.each(data.data, function (index, val) {
                    $("#suixingfuShopNum").append("<option value='" + val.suixingfuShopNum + "'>" + val.suixingfuShopNum.substr(-4)+"(完整商户号:"+val.suixingfuShopNum+")"+ "</option>");
                });
                form.render('select');
            }
        });
    }
    //初始化页面
    $(function () {

        setTimeout(() =>{
            BtyPaymentOrderYybb.searchSuixingfu();

            BtyPaymentOrderYybb.search();
        },100);

    });
});
